package com.example.emptytest;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

import android.widget.Button;
import android.widget.ExpandableListView;


import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.emptytest.Adapter.MyExpandableListAdapter;
import com.example.emptytest.DB.SQLiteHelper;
import com.example.emptytest.Fragment.Fragment_0;
import com.example.emptytest.Fragment.Fragment_1;
import com.example.emptytest.Fragment.Fragment_2;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;


public class Homepage extends AppCompatActivity {

    private SlidingMenu menu;
    private Button mBtn_menu;
    private Button mBtn_exit;
    private Button mBtn_home;
    private TextView mBtn_backMain;
    private LinearLayout mBtn_menulist01;
    private LinearLayout mBtn_menulist02;
    private ExpandableListView menu_list;
    private MyExpandableListAdapter MyListAdapter;
    private String STNum;
    private TextView sliding_STNum,sliding_STName;
    private SQLiteHelper helper;
    private Cursor cursor;
    //定义一个变量，来标识系统秒
    private long exitTime=0;

    //Fragment_container
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private Fragment current_Fragment;
    private Fragment target_Fragment;
    //private Fragment[][] fragmentgroup = new Fragment[4][4];
    // List Data
    String[] group = {"个人中心","管理员"};
    String[][] child = {
            {"修改个人信息","我的通知"},
            {"社团管理","后台管理"}
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent mIntent = getIntent();
        STNum=(String) mIntent.getSerializableExtra("STNum");
        helper = new SQLiteHelper(this);
        setContentView(R.layout.activity_homepage);
        //hideBottomUIMenu();
        initView();
        listener();
        fragment_init();
    }

    private void fragment_init() {
        manager = getSupportFragmentManager();
        transaction = manager.beginTransaction();
        current_Fragment = new Fragment_0();
        transaction.add(R.id.frag_container, current_Fragment);
        transaction.commit();
    }


   
    private void initView() {
        // menu
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.RIGHT);
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);

        menu.setBehindOffset(140);
        menu.setFadeDegree(0.35f);

        menu.attachToActivity(this,SlidingMenu.SLIDING_WINDOW);
        menu.setMenu(R.layout.sliding_right);

        mBtn_exit = findViewById(R.id.btn_exit);
        mBtn_menu = findViewById(R.id.menuBtn);
        // menu_list
        menu_list = findViewById(R.id.menu_list);
        MyListAdapter = new MyExpandableListAdapter(group,child,this);
        menu_list.setAdapter(MyListAdapter);
        // button
        mBtn_home = findViewById(R.id.homeBtn);

        mBtn_menulist01 = findViewById(R.id.list01);
        mBtn_menulist02 = findViewById(R.id.list02);

        sliding_STNum = menu.findViewById(R.id.sliding_STNum);
        sliding_STName = menu.findViewById(R.id.sliding_STName);
        System.out.println("SlidingID:"+sliding_STNum);
        mBtn_backMain = findViewById(R.id.backtoMain);

    }
    private void listener() {
        // menu
        mBtn_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //为侧滑菜单设置布局
                menu.toggle();
                System.out.println("SlidingID:"+sliding_STNum);

                String args[] = new String[]{"%" + STNum + "%"};
                cursor = helper.query(args);
                if(cursor.moveToFirst()) {//cursor读取数据
                System.out.println("SlidingID:"+sliding_STNum);
                    sliding_STName.setText(cursor.getString(cursor.getColumnIndex("STName")));
                    sliding_STNum.setText(cursor.getString(cursor.getColumnIndex("STNum")));
                }

            }
        });
        // menu_list
        // 侧边栏监听
        // level 1
        menu_list.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                //Toast.makeText(Homepage.this, group[groupPosition], Toast.LENGTH_SHORT).show();
                //返回false 否则一级列表不会展开
                return false;
            }
        });
        // level 2
        menu_list.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                    Toast.makeText(Homepage.this, child[groupPosition][childPosition], Toast.LENGTH_SHORT).show();
                    String teststring = "com.example.emptytest.Fragment_" + groupPosition + "_" + childPosition;
                    try {
                        Fragment c = (Fragment) Class.forName(teststring).newInstance();
                        target_Fragment = c;
                        Bundle bundle = new Bundle();
                        bundle.putString("STNum",STNum);
                        target_Fragment.setArguments(bundle);
                        switchFragment(target_Fragment);
                        menu.toggle();

                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                    //需要一个hide()

                return false;
            }
        });

        mBtn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(Homepage.this);
                builder.setTitle("退出");
                builder.setMessage("确定退出吗？");
                builder.setNegativeButton("取消",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });
                builder.setPositiveButton("确定",new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        finish();
                    }
                });

                builder.create().show();
            }
        });

        mBtn_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                target_Fragment = new Fragment_0();
                switchFragment(target_Fragment);
            }
        });

        mBtn_menulist01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),
                        "list01", Toast.LENGTH_SHORT).show();
                target_Fragment = new Fragment_1();
                switchFragment(target_Fragment);
                menu.toggle();
            }
        });

        mBtn_menulist02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),
                        "list02", Toast.LENGTH_SHORT).show();
                target_Fragment = new Fragment_2();
                switchFragment(target_Fragment);
                menu.toggle();
            }
        });

        mBtn_backMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Homepage.this,MainActivity.class);
                startActivity(intent);
                Toast.makeText(Homepage.this, "注销成功", Toast.LENGTH_SHORT).show();
                Homepage.this.finish();
            }
        });
    }
    // 重写返回
    @Override
    public boolean onKeyDown(int keyCode,KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            exit();
            return false;
        }
        return super.onKeyDown(keyCode,event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(),
                    "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        }
        else{
                finish();
                System.exit(0);
            }
        }

        // 切换Fragment
        private void switchFragment(Fragment targetFragment) {
            FragmentTransaction transaction = getSupportFragmentManager()
                    .beginTransaction();
            if (!targetFragment.isAdded()) {
                transaction
                        .hide(current_Fragment)
                        .add(R.id.frag_container, targetFragment)
                        .commit();
                System.out.println("还没添加呢");
            } else {
                transaction
                        .hide(current_Fragment)
                        .show(targetFragment)
                        .commit();
                System.out.println("添加了( ⊙o⊙ )哇");
            }
            current_Fragment = targetFragment;
        }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

}